#ifndef __Relay_Control_C
#define __Relay_Control_C

#include "Relay_Control.h"

void Rly_init(void){
	  GPIO_Config_T  configStruct;
    RCM_EnableAPB2PeriphClock(Rly_RTC);
    configStruct.pin = Rly1_PinId;
    configStruct.mode = GPIO_MODE_OUT_PP;
    configStruct.speed = GPIO_SPEED_50MHz;
    GPIO_Config(Rly_PinPort, &configStruct);
	  // 初始化置位
	  Rly_PinPort -> BC = Rly1_PinId;
	
	  #ifdef Has_RlyPin_Maintaining
	  RCM_EnableAPB2PeriphClock(Rly2_RTC);
    configStruct.pin = Rly2_PinId;
    GPIO_Config(Rly2_PinPort, &configStruct);	
	  // 初始化置位
	  Rly2_PinPort -> BC = Rly2_PinId;
	  #endif
	
}

void Rly_on(){
	  if(chgForbid == 0){
        #if Non_Plug_And_Charge > 0
			  if(startChg_External_Reason == 0){
					  return;
				}
        #endif		  
			  Rly_PinPort -> BSC = Rly1_PinId;
			  #ifdef Has_RlyPin_Maintaining
	      Rly2_PinPort -> BSC = Rly2_PinId;			  
	      #endif
			  // 记录充电数据：
				if(chg_start_tm == 0){
					  #if RTC_ON > 0
						getTimestampRTC();
						#endif
						chg_start_tm  = system_time;
					  chg_stage = CHG_StartUP;
				}
				// 记录继电器闭合时间;
				#if RTC_ON > 0
				getTimestampRTC();
				#endif
				Relay_ON_tm  = system_time;				
				// 充电日志保存
				#if LOG_ON > 0
				if(Rly_status != 1){
						#if RTC_ON > 0
							getTimestampRTC();
						#endif
						log_temp.occTime  = system_time / 1000;
						log_temp.logGrade = Log_Info;                // 信息级别;
						log_temp.logEvent = logEvt_ChargeStart;      // 开启充电;
						log_temp.logEvtData = 0;                     // 充电数据;
						if(log_data_append(log_temp)){
							  writeData[FWD_LogsSize_idx].intData = (uint32_t)Log_Saved_Sum; // 更新Log总数
								// 数据保存
								flash_write();
								flash_log_write();
						}						
				}					
				#endif
				// 插座状态
				Rly_status = 1;
		}
}

void Rly_off(){	
	  Rly_PinPort -> BC = Rly1_PinId; //置0
	  #ifdef Has_RlyPin_Maintaining
	  Rly2_PinPort -> BC = Rly2_PinId;
    Rly_startup_status = 0;	
    chg_stage = CHG_STOP;	
	  #endif
	  // 继电器关闭：
	  Relay_ON_tm  = 0;
	  // 日志记录
	  #if LOG_ON > 0
		if(Rly_status != 0){
				#if RTC_ON > 0
					getTimestampRTC();
				#endif
				log_temp.occTime  = system_time / 1000;
				log_temp.logGrade = Log_Info;               // 信息级别;
				log_temp.logEvent = logEvt_ChargeStop;      // 关闭充电;
				log_temp.logEvtData = 0;                    // 相关数据;
				if(log_data_append(log_temp)){
					  writeData[FWD_LogsSize_idx].intData = (uint32_t)Log_Saved_Sum; // 更新Log总数
						// 数据保存
						flash_write(); 
						flash_log_write();	
				}							
		}
		#endif
	  // 插座状态
		Rly_status = 0;
}

#ifdef Has_RlyPin_Maintaining
// 关闭启动引脚
void Rly_release_startup_Pin(){
	  Rly_PinPort -> BC = Rly1_PinId; //置0
    // 启动引脚 Rly1_PinId 释放标志;
		Rly_startup_status = 2;	
}
#endif

#endif
